/**
 * Created by Zhao Bo En on 2017/12/07
 */
//日期转换（时间戳转日期）
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


var startTime = null;       //开始时间，表格导出数据使用
var endTime = null;         //结束时间，表格导出数据使用
var farmName = null;       //电场名称，表格导出数据使用
var fileName = null;

$(function () {
    //$.ajaxSettings.async = false;
    loadTower();//加载测风塔
    dateTiemSelect();
    //load();
    $("#query").click(function () {
        load();
        // alert("111");
        /*if($("#startTime").val()===""){
            layer.msg("输入开始时间！", {icon: 2});
            $("#endTime").val("");
        }
        var startTime = new Date($("#startTime").val().replace(/\-/g, "\/"));
        var endTime = new Date($("#endTime").val().replace(/\-/g, "\/"));
        if(startTime >=endTime){
            layer.msg("开始时间不能大于结束时间！", {icon: 2});
            $("#startTime").val("");
            $("#endTime").val("");
            return false;
        }else {
            load();
        }*/
    });


    var aa = $('#selectFarm', window.parent.document).find("option:selected").text();
    console.log(aa);
    //  fileName = aa.substring(31,aa.length);
    // console.log(fileName);
    startTime = $("#startTime").val();
    endTime = $("#endTime").val();

    var table = new tableFactory(startTime,endTime,aa);
});
//点击时间查询
function dateTiemSelect(){
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render({
            elem: '#startTime', //新增的日期
            type: 'date',//日期类型date表示年月日
            /*  trigger: 'click',//如果绑定的元素非输入框，则默认事件为：click*/
            theme: '#20284D',//自定义主题
            min: '2014-1-1',//限制最小日期
            max: '2028-12-31'//限制最大日期
        });
        laydate.render({
            elem: '#endTime', //新增的日期
            type: 'date',
            theme: '#20284D',//自定义主题
            max: '2028-12-31',//限制最大日期
            ready: function(date){
                //console.log(date); //得到初始的日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            },
            /*change: function(value, date, endDate){ //日期时间被切换后的回调
                console.log(value); //得到日期生成的值，如：2017-08-18
                console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            }*/
            done: function(value, date, endDate){//选中之后的对调函数
                //得到日期生成的值，如：2017-08-18
                // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                //console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
                /*if($("#startTime").val()===""){
                    layer.msg("输入开始时间！", {icon: 2});
                    $("#endTime").val("");
                }
                var startTime = new Date($("#startTime").val().replace(/\-/g, "\/"));
                var endTime = new Date(value.replace(/\-/g, "\/"));
                if(startTime >=endTime){
                    layer.msg("开始时间不能大于或等于结束时间！", {icon: 2});
                    $("#startTime").val("");
                    $("#endTime").val("");
                    return false;
                }else {
                    load();
                }*/
            }
        });
    });
}

function loadTower(){
    $("#tower").empty();//赋值之前，先清空
    var me = this;
    var index = layer.load(1);
    var farmid = $('#selectFarm', window.parent.document).val();
    var news = $("#tower");//获取测风塔对象
    var data = {"farmid":farmid};
    $.ajax({
        url : "../windCurvesManage/getTower",
        type : "get",
        async:false,
        contentType : "application/json",
        dataType : "json",
        data :data /*JSON.stringify(data)*/,//转换成字符串。后台使用了RequestBody注解
        success : function(data) {
            if(data.listTowerno.length>0){
                for(var i = 0;i<data.listTowerno.length;i++){
                    if(data.listTowerno[i] == data.thisTowerno){
                        news.append('<option value="'+data.listTowerno[i]+'" selected = "selected">'+data.listTowermodel[i]+'</option>');
                    }else {
                        news.append('<option value="'+data.listTowerno[i]+'">'+data.listTowermodel[i]+'</option>');
                    }
                }

            }else {
                news.append('<option value="'+404404404+'">'+'无'+'</option>');
            }


            $("#tower").selectpicker('refresh');
            load();
            layer.close(index);
        }
    });
    $("#tower").selectpicker();
}

//初始化加载风频率数据
function load() {
    var index = layer.load(1);
    var WfMetSkAll = new Array(); //所有
    var WfMetSkDay = new Array();//日风频率
    var WfMetSkWeek = new Array(); // 周风频率
    var WfMetSkMonth = new Array(); // 月风频率
    var WfMetSkQuarter = new Array(); // 季风频率
    var WfMetSkYear = new Array(); // 年风频率
    var windFrequencyDay = new Array();
    var windFrequencyWeek = new Array();
    var windFrequencyMonth = new Array();
    var windFrequencyQuarter = new Array();
    var windFrequencyYear = new Array();
    var farmid = $('#selectFarm', window.parent.document).val();//获取父页面的元素
    var tower = $("#tower option:checked").val();
    var p = {
        //"startTime":$("#startTime").val(),
        "endTime":$("#endTime").val(),
        "farmid":farmid,
        "towerid":tower,
    };
    //获取实况数据
    $.ajax({    //获取数据(日)
        url : "../windFrequencyManage/selectAllForOneDayTime",
        type : "get",
        contentType : "application/json",
        dataType : "json",
        data : p,
        success : function(data) {
            for(var i = 0;i<data.length;i++){
                windFrequencyDay.push(data[i].toFixed(1))
            }
            WfMetSkDay=data;
            //lodaTu(windFrequencyDay,windFrequencyWeek,windFrequencyMonth,windFrequencyQuarter,windFrequencyYear);
            $.ajax({    //获取数据(周)
                url : "../windFrequencyManage/selectAllForOneWeekTime",
                type : "get",
                contentType : "application/json",
                dataType : "json",
                data : p,
                success : function(data) {
                    for(var i = 0;i<data.length;i++){
                        windFrequencyWeek.push(data[i].toFixed(1))
                    }
                    WfMetSkWeek=data;
                    //lodaTu(windFrequencyDay,windFrequencyWeek,windFrequencyMonth,windFrequencyQuarter,windFrequencyYear);
                    $.ajax({    //获取数据(月)
                        url : "../windFrequencyManage/selectAllForOneMonthTime",
                        type : "get",
                        contentType : "application/json",
                        dataType : "json",
                        data : p,
                        success : function(data) {
                            for(var i = 0;i<data.length;i++){
                                windFrequencyMonth.push(data[i].toFixed(1))
                            }
                            WfMetSkMonth=data;
                            //lodaTu(windFrequencyDay,windFrequencyWeek,windFrequencyMonth,windFrequencyQuarter,windFrequencyYear);
                            $.ajax({    //获取数据(季)
                                url : "../windFrequencyManage/selectAllForOneQuarterTime",
                                type : "get",
                                contentType : "application/json",
                                dataType : "json",
                                data : p,
                                success : function(data) {
                                    for(var i = 0;i<data.length;i++){
                                        windFrequencyQuarter.push(data[i].toFixed(1))
                                    }
                                    WfMetSkQuarter=data;
                                    //lodaTu(windFrequencyDay,windFrequencyWeek,windFrequencyMonth,windFrequencyQuarter,windFrequencyYear);
                                    $.ajax({    //获取数据(年)
                                        url : "../windFrequencyManage/selectAllForOneYearTime",
                                        type : "get",
                                        contentType : "application/json",
                                        dataType : "json",
                                        data : p,
                                        success : function(data) {
                                            for(var i = 0;i<data.length;i++){
                                                windFrequencyYear.push(data[i].toFixed(1))
                                            }
                                            WfMetSkYear=data;
                                            var cycle = ['日','周','月','季','年'];
                                            if(WfMetSkDay.length>0) {
                                                var a = {
                                                    cycle: cycle[0],
                                                    F1: WfMetSkDay[0].toFixed(1),
                                                    F2: WfMetSkDay[1].toFixed(1),
                                                    F3: WfMetSkDay[2].toFixed(1),
                                                    F4: WfMetSkDay[3].toFixed(1),
                                                    F5: WfMetSkDay[4].toFixed(1)
                                                };
                                                WfMetSkAll.push(a);
                                            }
                                            if(WfMetSkWeek.length>0) {
                                                var b = {
                                                    cycle: cycle[1],
                                                    F1: WfMetSkWeek[0].toFixed(1),
                                                    F2: WfMetSkWeek[1].toFixed(1),
                                                    F3: WfMetSkWeek[2].toFixed(1),
                                                    F4: WfMetSkWeek[3].toFixed(1),
                                                    F5: WfMetSkWeek[4].toFixed(1)
                                                };
                                                WfMetSkAll.push(b);
                                            }

                                            if(WfMetSkMonth.length>0) {
                                                var c = {
                                                    cycle: cycle[2],
                                                    F1: WfMetSkMonth[0].toFixed(1),
                                                    F2: WfMetSkMonth[1].toFixed(1),
                                                    F3: WfMetSkMonth[2].toFixed(1),
                                                    F4: WfMetSkMonth[3].toFixed(1),
                                                    F5: WfMetSkMonth[4].toFixed(1)
                                                };
                                                WfMetSkAll.push(c);
                                            }

                                            if(WfMetSkQuarter.length>0) {
                                                var d = {
                                                    cycle: cycle[3],
                                                    F1: WfMetSkQuarter[0].toFixed(1),
                                                    F2: WfMetSkQuarter[1].toFixed(1),
                                                    F3: WfMetSkQuarter[2].toFixed(1),
                                                    F4: WfMetSkQuarter[3].toFixed(1),
                                                    F5: WfMetSkQuarter[4].toFixed(1)
                                                };
                                                WfMetSkAll.push(d);
                                            }

                                            if(WfMetSkYear.length>0) {
                                                var e = {
                                                    cycle: cycle[4],
                                                    F1: WfMetSkYear[0].toFixed(1),
                                                    F2: WfMetSkYear[1].toFixed(1),
                                                    F3: WfMetSkYear[2].toFixed(1),
                                                    F4: WfMetSkYear[3].toFixed(1),
                                                    F5: WfMetSkYear[4].toFixed(1)
                                                };
                                                WfMetSkAll.push(e);
                                            }


                                            $("#windFrequencyManage").bootstrapTable("load", WfMetSkAll);
                                            lodaTu(windFrequencyDay,windFrequencyWeek,windFrequencyMonth,windFrequencyQuarter,windFrequencyYear);
                                            layer.close(index);
                                        },
                                    })
                                },
                            })
                        },
                    })
                },
            })
        },
    });
    //getWfMetForDay(p);
   // getWfMetForWeek(p);
    //getWfMetForMonth(p);
    //getWfMetForQuarter(p);
    //getWfMetForYear(p);


}


//表格样式
function tableFactory(startTime,endTime,fileNames) {
    var me = this;
    me.data = null;//有功功率
    me.windData = null;//电站信息
    var init = function () {
        $.when(me.getWindData()).then(function () {
            $("#windFrequencyManage").bootstrapTable({
                method: 'get',				  //请求方式（*）
                striped: true,					  //是否显示行间隔色
                cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,				   //是否显示分页（*）
                sortable: true,					 //是否启用排序
                sortOrder: "desc",				   //排序方式
                sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,					   //初始化加载第一页，默认第一页
                search: true,					   //是否显示表格搜索，只能进行客户端搜索
                strictSearch: false,                //true为全匹配，false为模糊查询
                showColumns: true,				  //是否显示筛选列按钮
                showRefresh: true,			  //是否显示刷新按钮
                clickToSelect:true,				//是否启用点击选中行
                showToggle: false,					//是否显示详细视图和列表视图的切换按钮
                cardView: false,					//是否显示详细视图
                detailView: false,				   //是否显示父子表
                singleSelect: true,                //是否支持多选,false表示支持多选，true表示不支持
                //undefinedText: '_',              //当数据为undefined时显示的字符
                height: 'auto',
                pageSize: 5,
                pageList: [5,20,30],
                editable:true,//是否可以行内编辑
                showExport: true,//是否显示导出按钮
                exportDataType:'all',//导出全部
                exportTypes:[  'csv'], //导出文件类型
                export: 'glyphicon-export icon-share',
                exportOptions:{
                    // ignoreColumn: [0,1],  //忽略某一列的索引
                    fileName:endTime+"_"+fileNames,  //文件名称设置
                    // worksheetName: 'sheet1',  //表格工作区名称
                    // tableName: '总台帐报表',
                    //  excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],
                    // onMsoNumberFormat: DoOnMsoNumberFormat
                },
                columns: [{
                    title: '周期',
                    field: 'cycle',
                    align: 'center',
                    valign: 'middle',

                },{
                    title: '0m/s-3m/s(%)',
                    field: 'F1',
                    align: 'center',
                    valign: 'middle',

                }, {
                    title: '3m/s-6m/s(%)',
                    field: 'F2',
                    align: 'center',
                    valign: 'middle',

                },{
                    title: '6m/s-9m/s(%)',
                    field: 'F3',
                    align: 'center',
                    valign: 'middle',

                },{
                    title: '9m/s-12m/s(%)',
                    field: 'F4',
                    align: 'center',
                    valign: 'middle',

                },
                    {
                        title: '12m/s以上(%)',
                        field: 'F5',
                        align: 'center',
                        valign: 'middle',

                    }],
                onEditableSave: function (field, row, oldValue, $el) {//编辑之后的事件
                    var p ={
                        id:row.fid,
                        power:row.power
                    }
                    $.ajax({
                        type: "post",
                        url: "../roseManage/edit",
                        data:row,//后台使用了实体类，前台就不能用Json.stringify
                        dataType: 'JSON',
                        success: function (data, status) {
                            /*if (status == "success") {
                                alert('提交数据成功');
                            }*/
                        },
                        error: function () {
                            alert('编辑失败');
                        },
                        complete: function () {

                        }

                    });
                }
            });
            //me.loadData();
            load();
        });
    }
    init();
}

tableFactory.prototype = {

    /*loadData: function () {
        var me = this;
        var index = layer.load(1);
        $.getJSON('/roseManage/selectAll', '', function (_data) {
            me.data = _data;
            $("#rose").bootstrapTable("load", _data);
            layer.close(index);
        })
    },*/

    //加载电站信息
    getWindData:function () {
        var me = this;
        $.getJSON('../windManage/selectAll', '', function (_data) {
            me.WindData = _data;
        })
    },
    getWindById: function (farmid) {
        var farmName = '';
        var me = this;
        $.each(me.WindData, function (index, item) {
            if (item.farmid === farmid) {
                farmName = item.farmname;
                return false;
            }
        });
        return farmName;
    }
}


//频率图
function lodaTu(windFrequencyDay,windFrequencyWeek,windFrequencyMonth,windFrequencyQuarter,windFrequencyYear) {
    var myChart = echarts.init(document.getElementById("main"));
    option = {
        title: {
            text: '风速频率统计',
            textStyle: {
                color: '#fff'
            }
        },
        toolbox: {
            show: true,
            feature: {
                /*mark: {show: true},
                dataZoom: {show: true},
                dataView: {show: true},
                magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore: {show: true},*/
                saveAsImage: {show: true}
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        legend: {
            data: ['日', '周', '月','季', '年'],
            selected:{
                '日':false,
                '周':false,
                '季':false,
                '年':false,
            },
            align: 'right',
            right: 10,
            textStyle: {
                color: '#fff',
                fontSize: 14
            },
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: ['0m/s-3m/s', '3m/s-6m/s', '6m/s-9m/s', '9m/s-12m/s', '12m/s以上'],
            axisLabel: {
                show: true,
                textStyle: {
                    color: '#fff'
                }
            }
        }],
        yAxis: [{
            type: 'value',
            name: '占比(%)',
            axisLabel: {
                formatter: '{value}',
                textStyle: {
                    color: '#fff'
                }
            }
        }],
        series: [{
            name: '日',
            type: 'bar',
            data: windFrequencyDay,
            barWidth: 15,
            itemStyle: {
                normal: {
                    barBorderRadius: 6,
                }
            },
        }, {
            name: '周',
            type: 'bar',
            //data: [10, 20, 5, 9, 3],
            data:windFrequencyWeek,
            barWidth: 15,
            itemStyle: {
                normal: {
                    barBorderRadius: 6,
                }
            },
        }, {
            name: '月',
            type: 'bar',
            //data: [1, 1, 2, 3, 1],
            data:windFrequencyMonth,
            barWidth: 15,
            itemStyle: {
                normal: {
                    barBorderRadius: 6,
                }
            },
        },{
            name: '季',
            type: 'bar',
            //data: [3, 7, 2, 3, 1],
            data:windFrequencyQuarter,
            barWidth: 15,
            itemStyle: {
                normal: {
                    barBorderRadius: 6,
                }
            },
        },
        {
            name: '年',
            type: 'bar',
            //data: [0.1, 2, 3, 1, 0.5],
            data:windFrequencyYear,
            barWidth: 15,
            itemStyle: {
                normal: {
                    barBorderRadius: 6,
                }
            },
        }]
    };
    myChart.setOption(option);
}
